package cn.xiaolang.function.file_manage.io;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 传统的字符流读写复制:
 * - FileReader+FileWriter
 * - BufferedWriter+BufferedReader
 * 注意:
 * <p>逐个字符读取,不能用来读取图片,音乐等文件,不然复制出来的文件打不开.而且复制出来的文件会变大.</p>
 *
 * @author Dean
 * @date 2022-01-06
 */
@Slf4j
public enum FileCopyCharEnum implements CharIOStream {

    /**
     * 字符流读写FileReader+FileWriter,相比起字节流的read,基本上把byte[]换成char[]即可
     */
    FILE_READER_WRITER("FileReader+FileWriter") {
        @Override
        public void transfer(InputStreamReader reader, OutputStreamWriter writer) {
            try {
                int b = 0;
                while ((b = reader.read()) != -1) {
                    writer.write(b);
                }
            } catch (Exception e) {
                log.error("", e);
            }
        }
    },
    /**
     * 对于文本文件,BufferedReader/Writer的复制速度是最快.
     * BufferedReader相比起FileReader有一个readLine()方法,可以每行读入,会比FileReader快.
     */
    BUFFERED_READER_WRITER("BufferedReader+BufferedWriter") {
        @Override
        public void transfer(InputStreamReader reader, OutputStreamWriter writer) {
            try (BufferedWriter bw = new BufferedWriter(writer);
                 BufferedReader br = new BufferedReader(reader)) {
                String line;
                int lineSize = 0;
                //网友推荐更加简洁的写法
                while ((line = br.readLine()) != null) {
                    bw.write(line + "\r\n");
                    // 把缓存区内容压入文件
                    bw.newLine();
                    if (lineSize % 500 == 0) {
                        bw.flush();
                    }
                    lineSize++;
                }
                bw.flush();

            } catch (Exception e) {
                log.error("", e);
            }
        }
    };

    @Getter
    private final String desc;

    FileCopyCharEnum(String desc) {
        this.desc = desc;
    }
}
